package com.slipper.common.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.spec.AlgorithmParameterSpec;
import java.util.Base64;

public class EncryptionDecrypt {

    public static String decrypt(String sessionKey, String ivData, String encryptedData) {
        byte[] encData = Base64.getDecoder().decode(encryptedData);
        byte[] iv = Base64.getDecoder().decode(ivData);
        byte[] key = Base64.getDecoder().decode(sessionKey);
        String strDecode;
        try {
            AlgorithmParameterSpec ivSpec = new IvParameterSpec(iv);
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
            cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
            strDecode = new String(cipher.doFinal(encData), StandardCharsets.UTF_8);
        } catch (Exception e){
            throw new RuntimeException(e);
        }

        //解析解密后的字符串
        if (!strDecode.isEmpty()) {
            JSONObject jsonObject= JSON.parseObject(strDecode);
            return jsonObject.get("phoneNumber").toString();
        }
        return "";

    }
}